# 健康习惯追踪路由
from flask import Blueprint, render_template, request, jsonify
from models import db
from models.health import Habit, HabitRecord
from datetime import datetime, date, timedelta
from sqlalchemy import func

health_bp = Blueprint('health', __name__, url_prefix='/health')

@health_bp.route('/')
def list_habits():
    """显示健康追踪页面"""
    return render_template('health.html')

@health_bp.route('/api/habits', methods=['GET'])
def get_habits():
    """获取所有习惯"""
    habits = Habit.query.filter_by(active=True).all()
    return jsonify({
        'habits': [habit.to_dict() for habit in habits]
    })

@health_bp.route('/api/habits', methods=['POST'])
def create_habit():
    """创建新习惯"""
    data = request.json
    
    habit = Habit(
        name=data['name'],
        description=data.get('description', ''),
        icon=data.get('icon', '📝'),
        target_count=data.get('target_count', 1),
        unit=data.get('unit', '次')
    )
    
    db.session.add(habit)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'habit': habit.to_dict()
    }), 201

@health_bp.route('/api/habits/<int:habit_id>', methods=['PUT'])
def update_habit(habit_id):
    """更新习惯"""
    habit = Habit.query.get_or_404(habit_id)
    data = request.json
    
    if 'name' in data:
        habit.name = data['name']
    if 'description' in data:
        habit.description = data['description']
    if 'icon' in data:
        habit.icon = data['icon']
    if 'target_count' in data:
        habit.target_count = data['target_count']
    if 'unit' in data:
        habit.unit = data['unit']
    if 'active' in data:
        habit.active = data['active']
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'habit': habit.to_dict()
    })

@health_bp.route('/api/habits/<int:habit_id>', methods=['DELETE'])
def delete_habit(habit_id):
    """删除习惯"""
    habit = Habit.query.get_or_404(habit_id)
    db.session.delete(habit)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@health_bp.route('/api/habits/<int:habit_id>/records', methods=['GET'])
def get_habit_records(habit_id):
    """获取习惯的打卡记录"""
    days = request.args.get('days', 30, type=int)  # 默认30天
    
    end_date = date.today()
    start_date = end_date - timedelta(days=days-1)
    
    records = HabitRecord.query.filter(
        HabitRecord.habit_id == habit_id,
        HabitRecord.date >= start_date,
        HabitRecord.date <= end_date
    ).all()
    
    return jsonify({
        'records': [record.to_dict() for record in records]
    })

@health_bp.route('/api/habits/<int:habit_id>/checkin', methods=['POST'])
def checkin_habit(habit_id):
    """打卡习惯"""
    data = request.json
    today = date.today()
    
    # 检查今日是否已打卡
    existing = HabitRecord.query.filter_by(
        habit_id=habit_id,
        date=today
    ).first()
    
    if existing:
        # 更新打卡次数
        existing.count = data.get('count', existing.count + 1)
        if 'notes' in data:
            existing.notes = data['notes']
    else:
        # 创建新打卡记录
        record = HabitRecord(
            habit_id=habit_id,
            date=today,
            count=data.get('count', 1),
            notes=data.get('notes', '')
        )
        db.session.add(record)
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '打卡成功'
    })

@health_bp.route('/api/habits/<int:habit_id>/stats', methods=['GET'])
def get_habit_stats(habit_id):
    """获取习惯统计信息"""
    habit = Habit.query.get_or_404(habit_id)
    
    # 总打卡天数
    total_days = HabitRecord.query.filter_by(habit_id=habit_id).count()
    
    # 当前连续天数（只有完成目标才算）
    today = date.today()
    streak = 0
    current_date = today
    
    while True:
        record = HabitRecord.query.filter_by(
            habit_id=habit_id,
            date=current_date
        ).first()
        
        # 只有完成目标次数才算有效打卡
        if record and record.count >= habit.target_count:
            streak += 1
            current_date -= timedelta(days=1)
        else:
            break
    
    # 本周完成率（只有完成目标的天数才算）
    week_start = today - timedelta(days=today.weekday())
    week_records = HabitRecord.query.filter(
        HabitRecord.habit_id == habit_id,
        HabitRecord.date >= week_start,
        HabitRecord.date <= today
    ).all()
    
    # 统计完成目标的天数
    week_completed_days = sum(1 for r in week_records if r.count >= habit.target_count)
    week_completion = (week_completed_days / 7) * 100
    
    # 本月完成率（只有完成目标的天数才算）
    month_start = today.replace(day=1)
    month_records = HabitRecord.query.filter(
        HabitRecord.habit_id == habit_id,
        HabitRecord.date >= month_start,
        HabitRecord.date <= today
    ).all()
    
    # 统计完成目标的天数
    month_completed_days = sum(1 for r in month_records if r.count >= habit.target_count)
    days_in_month = (today - month_start).days + 1
    month_completion = (month_completed_days / days_in_month) * 100
    
    # 今日是否已打卡（完成目标才算）
    today_record = HabitRecord.query.filter_by(
        habit_id=habit_id,
        date=today
    ).first()
    today_checked = today_record and today_record.count >= habit.target_count if today_record else False
    
    return jsonify({
        'total_days': total_days,
        'streak': streak,
        'week_completion': round(week_completion, 1),
        'month_completion': round(month_completion, 1),
        'today_checked': today_checked
    })

@health_bp.route('/api/dashboard', methods=['GET'])
def get_dashboard():
    """获取仪表板数据"""
    today = date.today()
    
    # 获取所有激活的习惯
    habits = Habit.query.filter_by(active=True).all()
    
    # 今日打卡情况
    today_checkins = []
    for habit in habits:
        record = HabitRecord.query.filter_by(
            habit_id=habit.id,
            date=today
        ).first()
        
        # 只有达到目标次数才算已完成
        is_completed = record and record.count >= habit.target_count if record else False
        
        today_checkins.append({
            'habit': habit.to_dict(),
            'checked': is_completed,  # 完成目标才算已打卡
            'count': record.count if record else 0
        })
    
    # 本周统计
    week_start = today - timedelta(days=today.weekday())
    week_data = []
    
    for i in range(7):
        current_date = week_start + timedelta(days=i)
        day_records = HabitRecord.query.filter_by(date=current_date).count()
        
        week_data.append({
            'date': current_date.isoformat(),
            'count': day_records
        })
    
    return jsonify({
        'today_checkins': today_checkins,
        'week_data': week_data,
        'total_habits': len(habits)
    })

